import Vue from 'vue'
import VueRouter from 'vue-router'

// 登录组件
import Login from '../components/Login'
// 首页组件
import Home from '../components/Home.vue'
// 欢迎组件
import Welcome from '../components/Welcome.vue'
// 用户列表组件
import Users from '../components/user/Users.vue'
// 权限列表
import Rights from '../components/power/Rights.vue'
// 角色列表
import Roles from '../components/power/Roles.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/Login',
    component: Login
  },
  {
    path: '/',
    redirect: '/Login'
  },
  {
    path: '/Home',
    component: Home,
    redirect: '/Welcome',
    children: [{
        path: "/Welcome",
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      }, {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 挂载路由导航守卫
// to 将要访问的路径
// from  从那个路径来
// next 是一个函数, 表示放行
// 1:next() 放行  2:next('/login') 强行跳转
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    return next()
  } else {
    //  获取token
    const tokenStr = window.sessionStorage.getItem('token')
    // 如果没有token,说明没有登录,强制踢到登录页
    if (!tokenStr) {
      window.alert("没有登录,请登录")
      return next('/login')
    } else {
      next()
    }
  }
})

export default router